<template slot-scope="scope">
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="myRequest"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-upload2 avatar-uploader-icon" />
    <template #tip>
      <div style="color:#bac0cd">支持扩展名：jpg、png，文件不得大于100kb</div>
    </template>
  </el-upload>
</template>

<script>
import { fileUpload } from '@/api/vm'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 < 100

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 100kb!')
      }
      return isJPG && isLt2M
    },
    // 覆盖原有的请求，改为自己的上传
    async myRequest({ file }) {
      try {
        const myPic = new FormData()
        myPic.set('fileName', file)
        const res = await fileUpload(myPic)
        // console.log(res)
        // 发送成功后进行图片的回显
        this.$emit('input', res)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    width: 84px;
    height: 84px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #999;
  }
  .avatar-uploader-icon {
    width: 84px;
    height: 84px;
    font-size: 28px;
    color: #8c939d;
    line-height: 84px;
    text-align: center;
    background-color: #f3f6fb;
  }
  .avatar {
    width: 84px;
    height: 84px;
    display: block;
  }
</style>
